<template>
  <el-dialog
    v-model="visible"
    title="错题科目管理"
    width="500px"
    @close="handleClose"
  >
    <div class="subject-manager">
      <!-- 添加科目表单 -->
      <div class="add-subject-form">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="科目名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入科目名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="handleAddSubject"
              :loading="loading"
            >
              添加科目
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 科目列表 -->
      <div class="subject-list">
        <el-divider content-position="left">已有科目</el-divider>
        <el-table :data="subjects" style="width: 100%">
          <el-table-column prop="name" label="科目名称" />
          <el-table-column prop="createdAt" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createdAt) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useMistakeStore } from '@/store/mistake'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const mistakeStore = useMistakeStore()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref()
const loading = ref(false)
const formData = ref({
  name: ''
})

const subjects = computed(() => mistakeStore.subjects)

const rules = {
  name: [
    { required: true, message: '请输入科目名称', trigger: 'blur' },
    { min: 1, max: 50, message: '科目名称长度在1-50个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 添加科目
const handleAddSubject = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true
    await mistakeStore.createSubject(formData.value)

    ElMessage.success('科目添加成功')
    formData.value.name = ''
    formRef.value.resetFields()
  } catch (error) {
    console.error('添加科目失败:', error)
    ElMessage.error(error.message || '添加科目失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formData.value.name = ''
  formRef.value?.resetFields()
}

// 监听对话框显示状态
watch(visible, async (newVal) => {
  if (newVal) {
    await mistakeStore.fetchSubjects()
  }
})

onMounted(async () => {
  await mistakeStore.fetchSubjects()
})
</script>

<style scoped>
.subject-manager {
  padding: 20px 0;
}

.add-subject-form {
  margin-bottom: 30px;
}

.subject-list {
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-divider__text) {
  background-color: #f5f5f5;
  padding: 0 10px;
}
</style>